import json
import tkinter as tk
from tkinter import ttk,messagebox
from PIL import Image, ImageTk

import CompletedQuestionnaireFrame
import IncompletedQuestionnaireFrame
from request_interface.req import find_qt_req


class WriteQuestionnaireFrame(tk.Toplevel):
    def __init__(self, parent):

        # 初始化属性
        self.value_str_var = tk.StringVar()

        super().__init__()

        self.parent = parent
        self.title("填写问卷详情")

        # 获取屏幕的宽和高
        sreen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()

        # 设置窗口的宽和高
        root_width = int(sreen_width / 2)
        root_height = int(screen_height / 2)

        # 使窗口居中
        self.geometry("{}x{}+{}+{}".format(
            root_width, root_height,
            int((sreen_width - root_width) / 2), int((screen_height - root_height) / 2)
        ))



        # 使用 Pillow 加载图像
        image = Image.open("Image/return.png")

        # 调整图像大小
        new_size = (25, 25)  # 设置新的尺寸 (宽度, 高度)
        resized_image = image.resize(new_size, Image.LANCZOS)
        photo = ImageTk.PhotoImage(resized_image)

        self.back_button = tk.Button(self, image=photo, text='返回', font=("宋体", 15), compound='left',
                                     command=self.back_to_main)
        self.back_button.photo = photo  # 保存图像对象的引用
        self.back_button.place(relx=0.01, rely=0.01, relwidth=0.15, relheight=0.1)

        self.entry_text = tk.Entry(self,textvariable=self.value_str_var)
        self.entry_text.place(relx=0.01, rely=0.12, relwidth=0.85, relheight=0.1)

        # 使用 Pillow 加载图像
        search_image = Image.open("Image/search.png")

        # 调整图像大小
        resized_search_image = search_image.resize(new_size, Image.LANCZOS)
        search_photo = ImageTk.PhotoImage(resized_search_image)
        self.search_button = tk.Button(self, image=search_photo, text='查询', compound='left', command=self.query_key_function)
        self.search_button.photo = search_photo  # 保存图像对象的引用
        self.search_button.place(relx=0.85, rely=0.12, relwidth=0.15, relheight=0.1)

        # 创建 Treeview
        # self.columns = ("问卷ID", "问卷名称","完成状态")
        self.columns = ("问卷名称")
        self.tree = ttk.Treeview(self, columns=self.columns, show="headings",height=5)

        # 定义列
        self.tree.heading("问卷名称", text="问卷名称", anchor=tk.CENTER)

        self.tree.column("问卷名称", width=400, anchor=tk.CENTER)

        # 示例数据
        self.questionnaires = {}

        # 添加数据到 Treeview
        # for q in self.questionnaires:
        #     # self.tree.insert("", tk.END, values=(q["问卷ID"], q["问卷名称"], q["完成状态"]))
        #     self.tree.insert("", tk.END, values=(q["template_name"]))


        # 绑定点击事件
        self.tree.bind("<Double-1>", self.on_treeview_click)

        # 创建滚动条
        self.scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscroll=self.scrollbar.set)
        self.tree.place(relx=0.01, rely=0.25, relwidth=0.95, relheight=0.7)
        self.scrollbar.place(relx=0.95, rely=0.25, relwidth=0.05, relheight=0.7)

    # def open_completed_questionnaire_frame(self):
    #     self.withdraw()
    #     completed_questionnaire_frame = CompletedQuestionnaireFrame.CompletedQuestionnaireFrame(self)
    #     completed_questionnaire_frame.mainloop()


    def open_incompleted_questionnaire_frame(self):
        self.withdraw()
        incompleted_questionnaire_frame = IncompletedQuestionnaireFrame.IncompletedQuestionnaireFrame(self,self.questionnaires)
        incompleted_questionnaire_frame.mainloop()

    #
    def open_questionnaire(self,event,questionnaire_id):
        print(f"Opening questionnaire with ID: {questionnaire_id}")
        # if questionnaire_completion_status == '已完成':
        #     print('s1')
        #     self.open_completed_questionnaire_frame()
        #
        # else:
        #     print('s2')
        #     self.open_incompleted_questionnaire_frame()
        self.open_incompleted_questionnaire_frame()

    def on_treeview_click(self,event):
        selected_item = self.tree.focus()  # 获取当前选择的行
        if selected_item:
            item = self.tree.item(selected_item)
            questionnaire_id = item['values'][0]  # 假设第一列是问卷的ID
            # questionnaire_completion_status = item['values'][2]  # 假设第一列是问卷的ID
            # self.open_questionnaire(event,questionnaire_id,questionnaire_completion_status)
            self.open_questionnaire(event,questionnaire_id)

    # 返回键功能
    def back_to_main(self):
        self.destroy()
        self.parent.deiconify()


    # 查询键功能
    def query_key_function(self):

        self.questionnaires=self.scan_find_qt_req()

        # 插入数据
        new_item=self.tree.insert("", tk.END, values=(self.questionnaires["template_name"]))

        # 更新数据
        self.tree.item(new_item,text=(self.questionnaires["template_name"]))

        self.on_submit()

    def on_submit(self):
        text = self.entry_text.get()
        messagebox.showinfo('Info', '查询完成')

    def scan_find_qt_req(self):
        print(self.value_str_var.get())
        resp=find_qt_req(self.value_str_var.get())

        self.value_str_var.set("")

        print(json.loads(resp))
        return json.loads(resp)

